//
//  EFCouponSegmentView.m
//  EnjogFood
//
//  Created by guocheng on 2017/5/7.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFCouponSegmentView.h"

@interface EFCouponSegmentView()

@property(nonatomic, strong)NSMutableArray *buttons;
@property(nonatomic, copy)ClickSegmentViewBlock block;

@end

@implementation EFCouponSegmentView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = RGBCOLOR(0xF5F9F9);
        self.buttons = [NSMutableArray array];
    }
    return self;
}

- (void)setSegmentArray:(NSArray *)array SelectIndex:(ClickSegmentViewBlock)block{
    self.block = block;
    [self.buttons removeAllObjects];
    NSInteger nCount = array.count;
//    self.bottomLine.width = 55;//(self.frame.size.width - 75.f)/nCount;
    for (int i = 0; i < nCount; i++) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width/nCount * i, 0, self.frame.size.width/nCount, self.height)];
        [btn setTitle:array[i] forState:UIControlStateNormal];
        [btn setTitleColor:kBlack333 forState:UIControlStateNormal];
        [btn setTitleColor:RGBCOLOR(0x69BA45) forState:UIControlStateSelected];
        btn.titleLabel.font = [UIFont systemFontOfSize:13.f];
        if (i == 0) {
            btn.selected = YES;
//            self.bottomLine.centerX = btn.centerX;
//            self.bottomLine.bottom = btn.bottom;
        }
        [btn addTarget:self action:@selector(onClickSegment:)forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        [self.buttons addObject:btn];
    }
}

- (void)onClickSegment:(UIButton *)btn{
    NSInteger index = [self.buttons indexOfObject:btn];
    if (self.block) {
        self.block(index);
    }
    [UIView animateWithDuration:0.3f animations:^{
//        self.bottomLine.centerX = btn.centerX;
    } completion:^(BOOL finished) {
        for (int i = 0; i < self.buttons.count; i++) {
            UIButton *tempBtn = self.buttons[i];
            tempBtn.selected = NO;
        }
        btn.selected = YES;
    }];
    
}
- (void)setSeletIndex:(NSInteger)index{
    for (int i = 0; i < self.buttons.count; i++) {
        UIButton *tempBtn = self.buttons[i];
        tempBtn.selected = NO;
    }
    UIButton *btn = self.buttons[index];
    btn.selected = YES;
}

@end
